/**
 * 函数列表获取接口测试用例
 *
 * Created by snowingsea on 2020/03/06.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/analyse-files/logic_bombs');

const files = require('./../../../../phoenix/models/files');

module.exports = describe('/GET files/:id/functions.json', function () {
  const administrator = new Administrator();
  const extensions = benchmark.config.languages.c.suffixes
    .concat(benchmark.config.headers.suffixes);
  let rootDirectory;
  let otherDirectoryId;
  const allFiles = [];
  const newUserIds = [];
  function url(fileId) {
    return `/files/${fileId}/functions.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((projectVersion) => {
        rootDirectory = projectVersion.rootDirectory;
        return projectVersion.updateVersionFiles(benchmark.files, benchmark.config);
      })
      .then(() => rootDirectory.analyse())
      .then(() => rootDirectory.getTree(extensions))
      .then((tree) => {
        common.should.be.fileTreeMessage(tree);
        common.should.be.equal.tree(tree.tree, benchmark.result.tree);
        const rootArray = [tree.tree];
        while (rootArray.length > 0) {
          const root = rootArray.pop();
          if (root.children) {
            root.children.forEach((child) => {
              rootArray.push(child);
            });
          }
          if (!otherDirectoryId) {
            otherDirectoryId = root.fileId;
          }
          allFiles.push(root);
        }
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求
  it('it should get functions', function (done) {
    const promises = allFiles.map((file) => {
      const { accessToken } = rootDirectory.projectVersion.project.creator.token;
      return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
        chai.request(uri)
          .get(url(file.fileId))
          .set('Authorization', `Bearer ${accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.functionsMessage(res.body);
            if (file.kind === files.kind.directory
              || file.status !== files.statusKind.compiled) {
              Object.keys(res.body.functions).length.should.be.eql(0);
            }
            resolve();
          });
      });
    });
    Promise.all(promises)
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 排序
  const sortByKeys = ['functionName'];
  const orders = ['asc', 'desc'];
  const options = [];
  sortByKeys.forEach((sortByKey) => {
    orders.forEach((order) => {
      options.push({ sortBy: sortByKey, order });
    });
  });
  options.forEach(function (option) {
    it(`it should sort functions by ${JSON.stringify(option)}`, function (done) {
      const promises = allFiles.map((file) => {
        const { accessToken } = rootDirectory.projectVersion.project.creator.token;
        return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
          chai.request(uri)
            .get(url(file.fileId))
            .set('Authorization', `Bearer ${accessToken}`)
            .query(option)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionsMessage(res.body);
              res.body.functions.should.be.sortedBy(option.sortBy, option.order === 'desc');
              if (file.kind === files.kind.directory
                || file.status !== files.statusKind.compiled) {
                Object.keys(res.body.functions).length.should.be.eql(0);
              }
              resolve();
            });
        });
      });
      Promise.all(promises)
        .then(() => {
          done();
        })
        .catch(done);
    });
  });

  // 不可获取不存在文件的函数列表
  it('it should fail to get functions when the file is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .get(url('000000000000000000000000'))
        .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可获取他人项目文件的函数列表
  it('it should fail to get functions when the project is not yours', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        newUser = newTester;
        return newTester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .get(url(otherDirectoryId))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
